// ref, ElMessage 已自动引入
// request 需要手动导入
import request from '@/utils/request'

/**
 * API请求的通用composable
 */
export function useApi() {
  const loading = ref(false)
  const error = ref(null)

  // 通用请求方法
  const execute = async apiCall => {
    loading.value = true
    error.value = null

    try {
      const result = await apiCall()
      return result
    } catch (err) {
      error.value = err
      ElMessage.error(err.message || '请求失败')
      throw err
    } finally {
      loading.value = false
    }
  }

  return {
    loading,
    error,
    execute
  }
}

/**
 * 用户相关的API
 */
export function useUserApi() {
  const { loading, error, execute } = useApi()

  // 获取用户列表
  const getUserList = (params = {}) => {
    return execute(() => request.get('/users', { params }))
  }

  // 获取用户详情
  const getUserDetail = id => {
    return execute(() => request.get(`/users/${id}`))
  }

  // 创建用户
  const createUser = userData => {
    return execute(() => request.post('/users', userData))
  }

  // 更新用户
  const updateUser = (id, userData) => {
    return execute(() => request.put(`/users/${id}`, userData))
  }

  // 删除用户
  const deleteUser = id => {
    return execute(() => request.delete(`/users/${id}`))
  }

  return {
    loading,
    error,
    getUserList,
    getUserDetail,
    createUser,
    updateUser,
    deleteUser
  }
}

/**
 * 文章相关的API
 */
export function useArticleApi() {
  const { loading, error, execute } = useApi()

  // 获取文章列表
  const getArticleList = (params = {}) => {
    return execute(() => request.get('/articles', { params }))
  }

  // 获取文章详情
  const getArticleDetail = id => {
    return execute(() => request.get(`/articles/${id}`))
  }

  // 创建文章
  const createArticle = articleData => {
    return execute(() => request.post('/articles', articleData))
  }

  // 更新文章
  const updateArticle = (id, articleData) => {
    return execute(() => request.put(`/articles/${id}`, articleData))
  }

  // 删除文章
  const deleteArticle = id => {
    return execute(() => request.delete(`/articles/${id}`))
  }

  return {
    loading,
    error,
    getArticleList,
    getArticleDetail,
    createArticle,
    updateArticle,
    deleteArticle
  }
}
